package org.example;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

public class UserManagementFrame extends JFrame {
    private final User currentUser;
    private JTable userTable;
    private DefaultTableModel tableModel;
    private List<User> userList;
    private JTextField idSearchField;
    private JTextField nameSearchField;

    public UserManagementFrame(User currentUser) {
        this.currentUser = currentUser;
        setTitle("用户管理 - " + currentUser.getRole());
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 创建查询面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        searchPanel.setBorder(BorderFactory.createTitledBorder("用户查询"));

        idSearchField = new JTextField(15);
        nameSearchField = new JTextField(15);
        JButton searchButton = new JButton("查询");
        JButton clearButton = new JButton("清空");
        JButton refreshButton = new JButton("刷新");

        searchPanel.add(new JLabel("用户ID:"));
        searchPanel.add(idSearchField);
        searchPanel.add(new JLabel("姓名:"));
        searchPanel.add(nameSearchField);
        searchPanel.add(searchButton);
        searchPanel.add(clearButton);
        searchPanel.add(refreshButton);

        add(searchPanel, BorderLayout.NORTH);

        // 创建表格模型
        String[] columnNames = {"用户ID", "姓名", "角色"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };

        userTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(userTable);
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加用户");
        JButton modifyButton = new JButton("修改用户");
        JButton deleteButton = new JButton("删除用户");
        JButton resetPasswordButton = new JButton("重置密码");

        buttonPanel.add(addButton);
        buttonPanel.add(modifyButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(resetPasswordButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 添加事件监听
        addButton.addActionListener(this::addUser);
        modifyButton.addActionListener(this::modifyUser);
        deleteButton.addActionListener(this::deleteUser);
        resetPasswordButton.addActionListener(this::resetPassword);
        searchButton.addActionListener(this::searchUsers);
        clearButton.addActionListener(e -> {
            idSearchField.setText("");
            nameSearchField.setText("");
            loadUserData();
        });
        refreshButton.addActionListener(e -> loadUserData());

        // 加载用户数据
        loadUserData();
    }

    private void loadUserData() {
        // 根据当前用户角色加载数据
        if ("admin".equals(currentUser.getRole())) {
            userList = UserDAO.getAllUsers();
        } else if ("teacher".equals(currentUser.getRole())) {
            userList = UserDAO.getStudents();
        }

        // 清空表格
        tableModel.setRowCount(0);

        // 填充表格
        for (User user : userList) {
            tableModel.addRow(new Object[]{
                    user.getId(),
                    user.getName(),
                    user.getRole()
            });
        }
    }

    private void addUser(ActionEvent e) {
        new AddUserDialog(this).setVisible(true);
    }

    private void modifyUser(ActionEvent e) {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的用户");
            return;
        }

        String userId = (String) tableModel.getValueAt(selectedRow, 0);
        User user = UserDAO.getUserById(userId);

        if (user != null) {
            new ModifyUserDialog(this, user).setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "未找到该用户信息");
        }
    }

    private void deleteUser(ActionEvent e) {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的用户");
            return;
        }

        String userId = (String) tableModel.getValueAt(selectedRow, 0);
        String userName = (String) tableModel.getValueAt(selectedRow, 1);

        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除用户 " + userId + " (" + userName + ") 吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {
            if (UserDAO.deleteUser(userId)) {
                tableModel.removeRow(selectedRow);
                JOptionPane.showMessageDialog(this, "删除成功");
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }

    private void resetPassword(ActionEvent e) {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要重置密码的用户");
            return;
        }

        String userId = (String) tableModel.getValueAt(selectedRow, 0);
        String userName = (String) tableModel.getValueAt(selectedRow, 1); // 修正为获取姓名列

        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要将用户 " + userId + " (" + userName + ") 的密码重置为123456吗？",
                "确认重置密码",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {
            // 重置密码
            String newPasswordHash = PasswordUtil.hashPassword("123456");
            // 使用新的重载方法
            if (UserDAO.updateUserPassword(userId, newPasswordHash)) {
                JOptionPane.showMessageDialog(this, "密码重置成功");
            } else {
                JOptionPane.showMessageDialog(this, "密码重置失败");
            }
        }
    }

    private void searchUsers(ActionEvent e) {
        String id = idSearchField.getText().trim();
        String name = nameSearchField.getText().trim();

        List<User> searchResult = UserDAO.searchUsers(id, name);
        tableModel.setRowCount(0);

        for (User user : searchResult) {
            tableModel.addRow(new Object[]{
                    user.getId(),
                    user.getName(),
                    user.getRole()
            });
        }
    }

    // 用于在添加或修改用户后刷新表格
    public void refreshTable() {
        loadUserData();
    }
}